package engine.video.blit;

public class PixelBuffer implements PixelBuffer_I {
	public PixelBuffer(int width, int height, byte[] pixels) {
		if(pixels == null) {
			throw new IllegalArgumentException("PixelBuffer(int, int, byte[])" +
					" - pixels cannot be null!");
		}
		if(width == 0 || height == 0) {
			throw new IllegalArgumentException("PixelBuffer(int, int, byte[])" + 
					" - width and height parameters MUST be greater than zero!");
		}
		
		Width = width;
		Height = height;
		Size = width * height;
		Pixels = pixels;
		
	}
	/**
	 * Converts this pixel buffer into an image suitable for blitting with a mask.
	 * @returns the generated mask.
	 **/
	public PixelBuffer generateMaskBuffer(byte keyColor) {
		int width = Width;
		int height = Height;
		byte[] imagePixels = Pixels;
		byte[] maskPixels = imagePixels.clone();
		
		// Generate an AND mask.
		byte sColor = (byte) 0x00; // Color for areas where the sprite is visible.
		byte mColor = (byte) 0xFF; // Color for areas where the sprite is transparent.
		
		for(int i = 0; i < maskPixels.length; i++) {
			// Convert mask sprite pixels into mask pixels.
			byte pixel = maskPixels[i];
			if(pixel == keyColor) {
				maskPixels[i] = mColor;
				// Convert the source sprite border pixels as well.
				imagePixels[i] = sColor;
			} else {
				maskPixels[i] = sColor;
			}
			
		}
		return new PixelBuffer(width, height, maskPixels);
	}
	
	public final int Width;
	public final int Height;
	public final int Size;
	public final byte[] Pixels;
	
	@Override
	public int getWidth() {
		return Width;
	}

	@Override
	public int getHeight() {
		return Height;
	}

	@Override
	public int getSize() {
		return Size;
	}
	

	@Override
	public byte[] getScan0() {
		return Pixels;
	}

}
